import os

from google.appengine.api import users           # google's user authentication (OpenID etc.)
from google.appengine.ext import db              # access to the google datastore
from google.appengine.ext.webapp import template # access to the django template system

import datastore                # for display of anonymous trees on the anonymous index

# Datastore models

class User(db.Model):
    userid = db.UserProperty()

    banned = db.BooleanProperty(default=False)
    admin = db.BooleanProperty(default=False)

    modified = db.DateTimeProperty(auto_now=True)
    modified_by = db.UserProperty(auto_current_user=True)
    created = db.DateTimeProperty(auto_now_add=True)
    created_by = db.UserProperty(auto_current_user_add=True)
    
#
# Public functions
#

# generate response from django template
def request_generate(self,template_name,template_values):
    path = os.path.join(os.path.dirname(__file__), template_name)
    self.response.out.write(template.render(path, template_values))

# authentication
def request_authorize(self, template_values, request_url):
    auth_text = 'login'
    auth_url = users.create_login_url(request_url)
    user = users.get_current_user()

    if user:
        nickname = user.nickname()
        email = user.email()

        auth_text = 'logout ' + nickname + ' <' + email + '>'
        auth_url = users.create_logout_url(request_url)
        
        # authenticate user
        authenticated = False
        query=User.all()
        query.filter('userid =', user)
        for q in query:
            if q.banned:
                self.response.out.write('<h3>Ur Banned!</h3><p>[banned user: &lt;'+email+'&gt;] <a href="'+auth_url+'">Login as another user</a>.</p>')
                return False
            authenticated = True
            break

        if not authenticated:
            self.redirect('/create_account')
            return False
    else:
        template_values = {'auth_url':auth_url, 'auth_text':auth_text}

        anontrees_query = datastore.Webtree.gql('WHERE anonymous = True ORDER BY name')
        anontrees = anontrees_query.fetch(256)
        template_values['anontrees'] = anontrees

        request_generate(self,'templates/index.html',template_values)
        return False

    # authentication succeeded after this line (with valid: auth_url, auth_text)
    template_values['auth_url'] = auth_url
    template_values['auth_text'] = auth_text
    return True


